package com.haieros.www.purerunshowsystem.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.IPackageInstallObserver;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.nio.charset.Charset;

/**
 * Created by admin on 2017/12/6.
 * 静默安装工具类
 */

public class SilentInstallUtils {

//    /**
//     * 不需要root权限 静默安装
//     * @param apkFile 文件
//     */
//    public static void NotRootInstall(File apkFile){
//        Log.e("TAG", "initforName:  判断apk是否存在："+apkFile.exists());
//        Class<?> clazz = null;
//        try {
//            clazz = Class.forName("android.os.ServiceManager");
//            Method method_getService = clazz.getMethod("getService",String.class);
//            IBinder bind = (IBinder) method_getService.invoke(null, "package");
//            IPackageManager iPm = IPackageManager.Stub.asInterface(bind);
//            //调用安装函数
//            iPm.installPackage(Uri.fromFile(apkFile), null, 2,apkFile.getName());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public static void installApk(File file, Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            @SuppressLint("PrivateApi") Method method = packageManager.getClass().getDeclaredMethod("installPackage",
                    new Class[]{Uri.class, IPackageInstallObserver.class, int.class, String.class});
            method.setAccessible(true);
            Uri apkUri = Uri.fromFile(file);
            Log.e("-------", "=====正在安装");
            method.invoke(packageManager, new Object[]{apkUri, new IPackageInstallObserver.Stub() {
                @Override
                public void packageInstalled(String pkgName, int resultCode) throws RemoteException {
                    Log.e("========升级信息", "packageInstalled = " + pkgName + "; resultCode = " + resultCode);
                }
            }, Integer.valueOf(2), "com.ali.babasecurity.yunos"});
            //PackageManager.INSTALL_REPLACE_EXISTING = 2;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行具体的静默安装逻辑，需要手机ROOT。
     * @param apkPath
     *          要安装的apk文件的路径
     * @return 安装成功返回true，安装失败返回false。
     */
    public static boolean install(String apkPath) {
        boolean result = false;
        File file = new File(apkPath);
        Log.e("TAG", "install 文件是否存在:     "+file.exists());
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        try {
            // 申请su权限
            Process process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            // 执行pm install命令
            String command = "pm install -r " + apkPath + "\n";
            dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
            dataOutputStream.flush();
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String msg = "";
            String line;
            // 读取命令的执行结果
            while ((line = errorStream.readLine()) != null) {
                msg += line;
            }
            Log.d("TAG", "读取命令的执行结果： install msg is " + msg);
            // 如果执行结果中包含Failure字样就认为是安装失败，否则就认为安装成功
            if (!msg.contains("Failure")) {
                result = true;
            }
        } catch (Exception e) {
            Log.e("TAG", e.getMessage(), e);
        } finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
            } catch (IOException e) {
                Log.e("TAG", e.getMessage(), e);
            }
        }
        return result;
    }
}
